package common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import serverSide.Param;

public class Command implements Serializable
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 6221571684516031649L;

	public enum CommandType
	{
		Get,
		Set
	}
	
	///command parameter
	private List<Param> commandParameter = null;
	
	private CommandType type;
	
	public List<Param> CommonParameter()
	{
		return commandParameter;
	}
	
	public CommandType getType()
	{
		return type;
	}
	
	public Command(CommandType cmdtype, Param ...data)
	{
		this.type = cmdtype;
		int i = data.length ;
		commandParameter = new ArrayList<>();
		for(int j = 0; j < i; j++)
			commandParameter.add(data[j]);
	}
	
	public byte[] toBytes() throws IOException
	{
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		ObjectOutputStream out = new ObjectOutputStream(output);
		out.writeObject(this);
		return output.toByteArray();
	}
	
	public static Command ParseFromBytes(byte[] data) throws ClassNotFoundException, IOException
	{
		Object o  =  new ObjectInputStream(new ByteArrayInputStream(data)).readObject();
		return (Command)o;
	}
	
//	public Command(byte[] source)
//	{
//		try {
//			String s = new String(source,"UTF-8");
//			String [] content = s.split("-");
//			
//			switch(content[0])
//			{
//				case "Get": type = CommandType.Get;
//				break;
//				case "Set": type = CommandType.Set;
//				break;
//			}
//			s = s.substring(content[0].length() + 1);
//			int length = 1;
//			try
//			{
//				content = s.split("*cmd*");
//				length = content.length;
//			}
//			catch(Exception io)
//			{
//				length = 0;
//			}
//			commandParameter = new ArrayList<>();
//			if(length != 0)
//			{
//				for(String i: content)
//				commandParameter.add(Param.Parse(i));
//			}
//			else
//			{
//				commandParameter.add(Param.Parse(s));
//			}
//		} catch (UnsupportedEncodingException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		
//	}
	
//	public byte[] ToBytes() throws UnsupportedEncodingException
//	{
//		String s = "" + type + "-";
//		for(Param i : commandParameter)
//			s += i.toString() + "*cmd*";
//		s = s.substring(0,s.length() - "*cmd*".length() );
//		return s.getBytes("UTF-8");
//	}
}
